﻿using System;
using System.Collections.Generic;
using System.Configuration;
using sdcc.FixYourStreetDotNet;

namespace CustomerContactSystem.WebForms {
    public partial class SettingsCheck : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            DoFysConnectionCheck();
            DoDatabaseCheck();
            DoAdminUsernameCheck();
            DoDefaultGroupCheck();
            DoDefaultRoleCheck();
            DoCategoryMatchUpsCheck();
            DoDefaultclassificationCheck();
            DoDefaultSubmitterCheck();
            DoDefaultRefereeCheck();
            DoDefaultSourceCheck();
        }

        private void DoFysConnectionCheck() {
            var fysUrl = ConfigSettings.FixYourStreetUrl;
            var fysFolder = ConfigSettings.FixYourStreetApiFolder;
            var fysVersion = ConfigSettings.FixYourStreetApiVersion;

            var fysClient = new FixYourStreetClient(fysUrl, fysFolder, fysVersion);

            try {
                var maxId = fysClient.GetIncidentIdLastUsed();
                FysConnectionCheck.Text = "Success! Last Id used for your Authority:" + maxId;
            }
            catch (Exception) {
                FysConnectionCheck.Text = "Failed - Cannot connect to " + fysUrl +
                                          " from server. Check your proxy settings.";
            }
        }

        private void DoDatabaseCheck() {
            try {
                var enqs = EnquiryRepository.QueryOver().List();
                DatabaseConnectionCheck.Text = "Success!";
            }
            catch (Exception) {
                DatabaseConnectionCheck.Text = "Failed! - Have you created your database and tables?";
            }
        }

        private void DoAdminUsernameCheck() {
            var user = UserRepository.QueryOver().Where(u => u.Username == ConfigSettings.AdminUsername).SingleOrDefault();
            AdminUsernameCheck.Text = user != null
                                          ? "Success!"
                                          : "Failed! - AdminUsername in web.config does not match a username in your user table.";
        }

        private void DoDefaultGroupCheck() {
            var userGroup = UserRepository.GetById(ConfigSettings.DefaultGroupId);
            DefaultGroupCheck.Text = userGroup != null
                                         ? "Success!"
                                         : "Failed! - DefaultGroupId in web.config does not match an Id in your UserGroups table";
        }

        private void DoDefaultRoleCheck() {
            var role = UserRoleRepository.GetById(ConfigSettings.DefaultRoleId);
            DefaultRoleCheck.Text = role != null
                                        ? "Success!"
                                        : "Failed! - DefaultRoleId in web.config does not match an Id in your UserRoles table";
        }

        private void DoCategoryMatchUpsCheck() {
            CategoryMatchUpsCheck.Text = "";
            var categoryIds = GetInternalCategoryMatchUpIds();
            foreach (var categoryId in categoryIds) {
                var category = EnquiryCategoryRepository.GetById(categoryId);
                if (category == null) {
                    CategoryMatchUpsCheck.Text += "No match found in EnquiryCategories table for Id " + categoryId + "<br />";
                }
            }

            if (CategoryMatchUpsCheck.Text.Length == 0) {
                CategoryMatchUpsCheck.Text = "Success!";
            }
            else {
                CategoryMatchUpsCheck.Text = "Failed!<br />" + CategoryMatchUpsCheck.Text;
            }
        }

        private static IEnumerable<int> GetInternalCategoryMatchUpIds() {
            var categoryIds = new List<int>();
            var configMatchUps = ConfigurationManager.AppSettings["CategoryMatchUps"];
            var matchUpPairings = configMatchUps.Split(',');

            foreach (var matchUpPairing in matchUpPairings) {
                var splitIds = matchUpPairing.Split(':');
                categoryIds.Add(int.Parse(splitIds[1]));
            }

            return categoryIds;
        }

        private void DoDefaultclassificationCheck() {
            var classification = EnquiryClassificationRepository.GetById(ConfigSettings.DefaultFysClassification);
            DefaultClassificationCheck.Text = classification != null
                                                  ? "Success!"
                                                  : "Failed! - DefaultFysClassification in web.config does not match an Id in your EnquiryClassification table";
        }

        private void DoDefaultSubmitterCheck() {
            var user = UserRepository.GetById(ConfigSettings.DefaultFysSubmitter);
            DefaultSubmitterCheck.Text = user != null
                                             ? "Success!"
                                             : "Failed! - DefaultFysSubmitter in web.config does not match an Id in your Users table";
        }

        private void DoDefaultRefereeCheck() {
            var user = UserRepository.GetById(ConfigSettings.DefaultFysReferee);
            DefaultRefereeCheck.Text = user != null
                                             ? "Success!"
                                             : "Failed! - DefaultFysReferee in web.config does not match an Id in your Users table";
        }

        private void DoDefaultSourceCheck() {
            var source = EnquirySourceRepository.GetById(ConfigSettings.FysSourceId);
            DefaultSourceCheck.Text = source != null
                                          ? "Success!"
                                          : "Failed! - FysSourceId does not match an Id in your EnquirySources table.";
        }
    }
}